import React from "react";
import {
  Form,
  Button,
  Input,
  Row,
  InputNumber,
  Utils,
  AppContainer,
} from "knowdesign";
import message from "@/components/Message";
import notification from "@/components/Notification";
import { FormMap } from "./config";
import Api from "../../api";
import { history, useModel } from "umi";
import { systemCipherKey } from "@/constants/common";
import HttpUtils from "@/utils/HttpUtils";
import { ApiResponse } from "./types/d";
import { ConfigPermissionMap, PermissionNode } from "../config/CommonConfig";
// import { systemCipherKey } from '@src/constants/common';

export enum FormItemType {
  input = "input",
  inputPassword = "inputPassword",
  inputNumber = "inputNumber",
  custom = "custom",
}

export interface IFormItem {
  key: string;
  type: FormItemType;
  attrs?: any;
  rules?: any[];
  invisible?: boolean;
  customFormItem?: any;
}

export const renderFormItem = (item: IFormItem) => {
  switch (item.type) {
    default:
    case FormItemType.input:
      return <Input key={item.key} {...item.attrs} />;
    case FormItemType.inputPassword:
      return <Input.Password key={item.key} {...item.attrs} />;
    case FormItemType.inputNumber:
      return <InputNumber key={item.key} {...item.attrs} />;
    case FormItemType.custom:
      return (item as IFormItem).customFormItem;
  }
};

export const LoginForm: React.FC<any> = (props) => {
  const [form] = Form.useForm();
  const [, setGlobal] = AppContainer.useGlobalValue();

  // 获取权限树
  const getPermissionTree = (userInfo, userId: number) => {
    const getUserInfo = Utils.request(`/logi-security/api/v1/user/${userId}`);
    const getPermissionTree = Utils.request(
      "/logi-security/api/v1/permission/tree"
    );

    Promise.all([getPermissionTree, getUserInfo]).then(
      ([permissionTree, userDetail]: [PermissionNode, any]) => {
        const allPermissions = permissionTree.childList;

        // 获取用户在系统管理拥有的权限
        const userPermissionTree = userDetail.permissionTreeVO.childList;
        const configPermissions = userPermissionTree.find(
          (sys) => sys.permissionName === ConfigPermissionMap.SYS_MANAGE
        );
        const userPermissions: ConfigPermissionMap[] = [];
        configPermissions &&
          configPermissions.childList.forEach(
            (node) => node.has && userPermissions.push(node.permissionName)
          );

        const hasPermission = (permissionName: ConfigPermissionMap) =>
          permissionName && userPermissions.includes(permissionName);

        setGlobal((curState: any) => ({
          ...curState,
          permissions: allPermissions,
          userPermissions,
          hasPermission,
          userInfo,
        }));
      }
    );
  };

  const handleSubmit = async ({
    userName,
    pw,
  }: {
    userName: string;
    pw: string;
  }) => {
    HttpUtils.post(Api.login, {
      userName,
      pw: Utils.encryptAES(pw, systemCipherKey),
    })?.then((res) => {
      if (res?.code === 200) {
        message.success("登录成功");
        localStorage.setItem("userInfo", JSON.stringify(res));
        getPermissionTree(res, res?.data?.id);
        const redirectPath =
          window.location.search.slice("?redirect=".length) || "/";
        history.replace(redirectPath);
      } else {
      }
    });
  };

  return (
    <>
      <Form
        name="normal_login"
        form={form}
        className="login-form"
        onFinish={handleSubmit}
        layout={"vertical"}
      >
        {FormMap.map((formItem) => {
          return (
            <Row key={formItem.key}>
              <Form.Item
                key={formItem.key}
                name={formItem.key}
                label={formItem.label}
                rules={formItem.rules}
                style={{ width: "100%" }}
              >
                {renderFormItem(formItem)}
              </Form.Item>
            </Row>
          );
        })}
        <Form.Item key={"submit"}>
          <Row>
            <Button className="submit-btn" type="primary" htmlType="submit">
              登录
            </Button>
          </Row>
        </Form.Item>
      </Form>
    </>
  );
};
